<?php

namespace app\modules\web\controllers;

use yii\web\Controller;
use \app\modules\web\controllers\common\BaseController;
use \app\models\market\MarketQrcode;
use \app\common\services\weixin\RequestServices;
class QrcodeController extends BaseController
{
   
    public function actionIndex()
    {
    	$list=MarketQrcode::find()->asArray()->all();
        return $this->render('index',['list'=>$list]);
    }
    public function actionSet()
    {
        if(\Yii::$app->request->isPOST){
            $name=$this->post('name','');
            $id=$this->post('id','');
            //判断名称是否存在
            $is_find=MarketQrcode::find()->where(['name'=>$name])->one();
            if($is_find){
                return $this->renderJson([],"已经存在");
            }
            //判断添加还是删除
            $is_find=MarketQrcode::find()->where(['id'=>$id])->one();
            
            if($is_find){
                $model_qrcode=$is_find;
                $model_qrcode->name=$name;
                $model_qrcode->updated_time=time();
            }else{
                $model_qrcode=new MarketQrcode();
                $model_qrcode->name=$name;
                $model_qrcode->created_time=time();
                
            }
            //获取二维码
            if($model_qrcode->save(0)){
                if(!$model_qrcode->qrcode){
                    $info=$this->getTmpQrcode($model_qrcode->id);
                    if($info){
                         
                        $model_qrcode->extra=json_encode($info);
                        $model_qrcode->qrcode=isset($info['url'])?$info['url']:'';
                        $model_qrcode->expired_time=isset($info['expire_seconds'])?$info['expire_seconds']+time():'';
                        $model_qrcode->update(0);
                    }
                   
                }
            }
            return $this->renderJson([],'操作成功');
        }
    	$id=$this->get('id','');
        return $this->render('set',['id'=>$id]);
    }
    //获取临时的二维码
    private function getTmpQrcode($id){
        $access_token=RequestServices::getAccessToken();
        $url='qrcode/create?access_token='.$access_token;
        $data=[
            "expire_seconds"=>604800,
            "action_name"=>"QR_SCENE",
            "action_info"=>
                [
                "scene"=>["scene_id"=>$id],
                ],
        ];
        return RequestServices::send($url,json_encode($data),'POST');
        
        
    }
}
